/**
 * Created by Yun on 2016-09-17.
 */
import React from 'react';
import {Input, Button} from 'antd';
import Text from '../components/Text';
import styles from './Editable.less';

export default class Editable extends React.Component {
  state = {
    value: this.props.value,
    editting: false,
  };
  onEdit = ()=>{
    this.setState({
      editting: true,
    });
  };
  onBlur = () => {
    this.setState({
      editting: false,
    });
  };
  onReturn = async ev=>{
    const { value } = ev.target;
    const { onEnter } = this.props;
    this.setState({
      editting: false,
    });
    await (onEnter && onEnter(value));
    this.setState({
      value,
    });
  };
  render() {
    const {type, autosize} = this.props;
    const {value, editting} = this.state;
    if (editting) {
      if (type === 'textarea') {
        return (
          <div>
            <Input
              className={styles.input} defaultValue={value}
              autosize={autosize} type={type}
              autoFocus onBlur={this.onReturn}
            />
            <Button type="primary" onClick={this.onReturn} >保存</Button>
          </div>
        );
      }
      return <Input
        className={styles.input} defaultValue={value}
        autosize={autosize} onPressEnter={this.onReturn} type={type}
        autoFocus onBlur={this.onReturn}
      />
    }
    return <div className={styles.text} onClick={this.onEdit}><Text>{`${value}`}</Text></div>
  }
}
